<template>
  <div class="page-container">
    <ex_super_table_page v-bind="option" ref="superTablePage">
      <template v-slot:action-right>
        <el-upload v-auth="'ums_customer_erp_config_import'" action="" :show-file-list="false" style="display: inline;" :http-request="uploadFile">
          <el-button slot="trigger" size="mini" type="primary">{{ $tt('label_import_excel') }}</el-button>
        </el-upload>
      </template>
    </ex_super_table_page>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="880px">

      <el-form ref="formEl" :model="formValue" :rules="rules" label-width="120px" class="common-form-panel-div"
               style="padding: 0px;">
        <el-form-item :label="$tt('label_current_customer')">
          <label>{{ formValue.customerName + '(' + formValue.customerCode + ')' }}</label>
          <br/>
          <label style="padding: 0px;color: red;">如果有多个平台客户编码，请使用英文逗号 " , " 分隔</label>
        </el-form-item>
        <ex_header_spiler :title="$tt('label_Configure_company')"></ex_header_spiler>

        <ex-table-auto class="el-table-nowwarp" ref="resourceDownloadGridPanelEl"
                       :data="platformList"
                       :autoFill="true"
                       border>

          <el-table-column prop="platformCode" :label="$tt('label_srm_api_service_platform_code')" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.platformCode }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="platformName" :label="$tt('label_srm_api_service_platform_name')" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.platformName }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column prop="platformCustomerCode" :label="$tt('label_srm_api_service_platform_customer_name')">-->
          <!--            <template slot-scope="scope">-->
          <!--              <el-input type="text" v-model="scope.row.platformCustomerCode"/>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column prop="platformCustomerCodeList" :label="$tt('label_srm_api_service_platform_customer_name')">
            <template slot-scope="scope">
              <el-input type="text" v-model="scope.row.platformCustomerCodeList"/>
            </template>
          </el-table-column>
        </ex-table-auto>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $tt('label_cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $tt('label_save') }}</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import superTablePageFunction from '@/mixin/super-table-page-function';

export default {
  title: 'title_ERP_customer_config',
  mixins: [superTablePageFunction],
  components: {},
  data() {
    return {

      dialogTitle: '',
      dialogFormVisible: false,
      formValue: {
        customerId: '',
        "isTest": 'N'
      },

      platformList: [],

      rules: {},
      diaOption: {},

      option: {
        //搜索框内容
        search: {
          //搜索框内容，key为搜索字段，label为标签提示
          model: [
            {label: "label_customer", key: "customerIds", type: 'common_customer_choose', attrs: {multiple: true,},},
          ],
        },
        action: [],
        actionExtra: [

          {label: 'label_download_excel_import_temp',auth:'ums_customer_erp_config_import', click: this.downloadImportTemp},
        ],

        table: {
          url: "/ums-api/customer/CustomerErpRefRpc/selectPage.json",
          attrs: {},
          model: [
            {
              key: 'companyCode', label: 'label_company_code',
            },
            {
              key: 'companyName', label: 'label_company_name',
            },
            {
              key: 'platformCodeMap', label: 'ERP映射', render: this.platformCodeMapRender
            },
            // {key: 'gmtCreate', label: 'label_create_time', attrs: {formatter: (r, c, v, i) => this.$dateFormat(v)},},
            {
              type: 'operate', width: 250, operate: [
                {
                  label: 'label_config', 
                  auth:'ums_customer_erp_config_edit',
                  click: (row) => {
                    this.dialogTitle = this.$tt('title_ERP_mapping')

                    this.formValue.customerId = row.id
                    this.formValue.customerCode = row.companyCode
                    this.formValue.customerName = row.companyName

                    this.dialogFormVisible = true
                  }
                }
              ],
            }
          ]

        }
      }

    };
  },
  watch: {
    'dialogFormVisible'(val, old) {
      if (val) {
        let _this = this

        if (this.formValue.customerId == '') {
          this.platformList = []
          return
        }

        _this.$ajax({
          url: '/open-api/open/OpenPlatformRpc/selectSimple.json',
          success: (res) => {
            if (res && res.data && res.data.rows) {
              this.platformList = res.data.rows

              // 查询已经配置的数据
              _this.$ajax({
                url: '/ums-api/customer/CustomerErpRefRpc/selectByParam.json',
                type: 'json',
                data: {
                  customerId: this.formValue.customerId,
                  platformCodes: res.data.rows.map((item) => {
                    return item.platformCode
                  })
                },
                success: (response) => {
                  if (response && response.data && response.data.rows) {

                    this.platformList.forEach((item) => {
                      let codeList = []
                      response.data.rows.forEach((item2) => {

                        if (item.platformCode === item2.platformCode) {
                          codeList.push(item2.platformCustomerCode)

                        }

                      })
                      // 英文逗号拆分
                      if (!_.isEmpty(codeList)) {
                        let platformCustomerCodeList = codeList.join(',')
                        this.$set(item, "platformCustomerCodeList", platformCustomerCodeList)
                      }
                    })
                  }
                }
              });
            } else {
              _this.platformList = []
            }
          }
        });
      }
    }
  },
  methods: {
    uploadFile(cfg) {
      this.$uploadFile({
        loading: true,
        url: this.$url['ums/ImportErpRef'],
        file: cfg.file,
        success: (res) => {
          this.$emitPage("oms>import_manage", 'reload')
          this.$confirm(this.$tt("tip_exporting_confirm_goto_recode_list"), this.$tt('label_tip'), {
            type: 'success'
          }).then(() => {
            this.$router.push({
              path: '/page/oms/report/import_manage',
            });
          }).catch(() => {
          });
        }
      })
    },
    downloadImportTemp() {
      if (this.$clickFast()) return
      this.$downloadFile({
        loading: true,
        url: this.$url['ums/downloadErpRefTemp']
      })

    },
    platformCodeMapRender(h, {row}) {
      if (row.platformCodeMap) {
        const out = []
        _.forOwn(row.platformCodeMap, (v, k) => {
          if (!!v) {
            out.push(`${k} : ${v}`)
          }
        })
        return out.map(it => h('div', it))
      }
      return ""
    },
    submitForm() {
      let _this = this

      if (_this.platformList && _this.platformList.length > 0) {

        // 赋值客户数据
        _this.platformList.forEach((item) => {
          item.id = ''
          item.customerId = _this.formValue.customerId
          item.customerCode = _this.formValue.customerCode
          item.customerName = _this.formValue.customerName
        })
        // platformCustomerCodeList 根据 , 拆分数据
        let newList = []
        _this.platformList.forEach((item) => {
          if (item.platformCustomerCodeList !== undefined && item.platformCustomerCodeList !== null && item.platformCustomerCodeList !== '') {
            let platformCustomerCodeList = item.platformCustomerCodeList.split(',')
            console.log(platformCustomerCodeList)
            if (platformCustomerCodeList && platformCustomerCodeList.length > 0) {
              platformCustomerCodeList.forEach((item2) => {
                let newItem = JSON.parse(JSON.stringify(item))
                if (item2 === '') {
                  return
                }
                newItem.platformCustomerCode = item2
                newList.push(newItem)
              })
            }

          }
        })

        // 保存数据
        _this.$ajax({
          url: '/ums-api/customer/CustomerErpRefRpc/saveBatch.json',
          type: 'json',
          data: {refList: newList},
          success: (responseData) => {
            _this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
            _this.$refs['superTablePage'].reload()
            _this.dialogFormVisible = false
          }
        });
      }


    }


  },


}
</script>

<style scoped>

</style>
